package com.sun.async.service.impl;

import com.sun.async.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 文件存储服务实现类
 */
@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Override
    public String getUploadPath() {
        return Paths.get(uploadDir).toAbsolutePath().normalize().toString();
    }

    @Override
    public String saveFile(MultipartFile file) throws IOException {
        // 创建存储目录（如果不存在）
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = StringUtils.cleanPath(System.currentTimeMillis() + "_" + file.getOriginalFilename());
        Path targetLocation = uploadPath.resolve(fileName);

        // 保存文件
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    }

    @Override
    public String getRelativePath(String fileName) {
        return uploadDir + "/" + fileName;
    }

    @Override
    public String getAbsolutePath(String relativePath) {
        return Paths.get(uploadDir, relativePath).toAbsolutePath().normalize().toString();
    }

    @Override
    public void downloadFile(String relativePath, java.io.OutputStream outputStream) throws IOException {
        Path filePath = Paths.get(relativePath);
        Files.copy(filePath, outputStream);
    }

}